package com.sso.ssosystem1.controller;


import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.bind.annotation.RequestParam;
//import org.thymeleaf.util.StringUtils;

@Controller

// 页面跳转逻辑
@RequestMapping("/view")
public class ViewController {
    
    @Autowired
    //注入
    private RestTemplate restTemplate;

    private final String LOGIN_INFO_ADDRESS = "http://login.sso.com:8080/login/info?token=";
    /**
     * 跳转到第一个系统
     * @return
     * 
     */
    @GetMapping("/index")
    public String toSystem1(@CookieValue(required = false,value = "TOKEN")Cookie cookie, 
                            HttpSession session){
         
        String target="http://system1.sso.com:8081/view/index";


            if(cookie != null){
                //从首页获取的用户信息
                String token = cookie.getValue();
                if(!StringUtils.isEmpty(token)){
                    Map result = restTemplate.getForObject( LOGIN_INFO_ADDRESS + token,Map.class);
                    session.setAttribute("loginUser", result);
                    return "index";
                }
                else{
                    return "redirect:http://login.sso.com:8080/view/login?target="+target;
                }
                
            }
        
        return "redirect:http://login.sso.com:8080/view/login?target="+target;
        
        

    }
}